// 导入对象存储工具函数
const { getObjectURL, getDefaultAvatarURL, getSystemIconURL } = require('../../utils/storage');

Page({
  // 页面初始数据
  data: {
    // 这些URL直接硬编码在WXML中，这里保留作为备份
    iconUrls: {
      systemNotice: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/text/System%20icon/%E7%B3%BB%E7%BB%9F%E9%80%9A%E7%9F%A5.svg',
      watchCollect: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/text/System%20icon/%E5%9B%B4%E8%A7%82%E4%B8%8E%E6%94%B6%E8%97%8F.svg',
      comments: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/text/System%20icon/%E8%AF%84%E8%AE%BA%E4%B8%8E@.svg',
      customerService: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/text/System%20icon/%E7%B3%BB%E7%BB%9F%E5%AE%A2%E6%9C%8D.svg'
    },
    avatarUrls: {
      avatar1: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/text/Default%20avatar/d907281-0.png',
      avatar2: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/text/Default%20avatar/d907281-1.png',
      avatar3: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/text/Default%20avatar/d928162-0.png',
      avatar4: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/text/Default%20avatar/d928162-1.png'
    },
    activeTab: 'all', // 当前选中的标签页：all, group, personal
    showMenu: false, // 是否显示长按菜单
    currentChat: {}, // 当前长按选中的聊天
    isPinned: false, // 当前聊天是否置顶
    isMuted: false, // 当前聊天是否静音
    searchKeyword: '', // 搜索关键词
    totalUnread: 0, // 所有未读消息总数
    groupUnread: 0, // 群聊未读消息总数
    personalUnread: 0, // 私聊未读消息总数
    
    // 模拟数据，实际应该从服务器获取
    chatList: [
      // 个人聊天
      { 
        id: 1, 
        type: 'personal', 
        name: '孟征源', 
        avatar: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/text/Default%20avatar/d907281-0.png',
        lastMessage: '明天数据结构课后我们图书馆讨论一下大作业吧，我找到一些参考资料',
        time: '2025-03-21',
        unread: 0
      },
      { 
        id: 2, 
        type: 'personal', 
        name: '余翔宇', 
        avatar: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/text/Default%20avatar/d907281-1.png',
        lastMessage: '学院下周的编程比赛你报名了吗？我们可以组队参加',
        time: '2025-03-21',
        unread: 3
      },
      
      // 群聊
      { 
        id: 1, 
        type: 'group', 
        name: 'JAVA讨论群', 
        avatar: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/text/Default%20avatar/d907281-0.png',
        lastMessage: '伍家旺：解决了那个线程安全问题，关键在于使用synchronized块而不是方法',
        time: '2025-03-21',
        unread: 12,
        memberCount: 32,
        groupType: 'study',
        isMuted: true,
        isPinned: false
      },
      { 
        id: 2, 
        type: 'group', 
        name: '算法竞赛小组', 
        avatar: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/text/Default%20avatar/d907281-1.png',
        lastMessage: '李明：今天的LeetCode每日一题已经解决，思路已经上传到群文件',
        time: '08:45',
        unread: 5,
        memberCount: 15,
        groupType: 'project',
        isMuted: false,
        isPinned: true
      },
      { 
        id: 3, 
        type: 'group', 
        name: '校园开放日筹备组', 
        avatar: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/text/Default%20avatar/d907281-0.png',
        lastMessage: '[群公告] 本周六开放日活动安排已经确定，请查看置顶消息',
        time: '昨天',
        unread: 5,
        memberCount: 28,
        groupType: 'activity',
        isMuted: true,
        isPinned: false
      },
      { 
        id: 4, 
        type: 'group', 
        name: '毕业设计交流群', 
        avatar: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/text/Default%20avatar/d928162-0.png',
        lastMessage: '张教授：下周三将举行毕业设计中期检查，请各位同学做好准备',
        time: '3月20日',
        unread: 2,
        memberCount: 45,
        groupType: 'study',
        isMuted: false,
        isPinned: false
      }
    ]
  },
  
  // 生命周期函数--监听页面加载
  onLoad: function(options) {
    console.log('消息页面加载');
    this.calculateUnreadCounts();
  },
  
  // 计算未读消息数量
  calculateUnreadCounts: function() {
    // 模拟数据，实际应该从服务器获取
    const mockData = [
      // 个人聊天
      { type: 'personal', unread: 1 }, // 陈明辉
      { type: 'personal', unread: 3 }, // 余翔宇
      { type: 'personal', unread: 2 }, // 金波
      { type: 'personal', unread: 1 }, // 伍慧嘉
      { type: 'personal', unread: 6 }, // 张三
      { type: 'personal', unread: 4 }, // 徐一
      
      // 群聊
      { type: 'group', unread: 12 }, // JAVA讨论群
      { type: 'group', unread: 5 },  // 算法竞赛小组
      { type: 'group', unread: 5 },  // 校园开放日筹备组
      { type: 'group', unread: 2 },  // 毕业设计交流群
    ];
    
    let totalUnread = 0;
    let groupUnread = 0;
    let personalUnread = 0;
    
    mockData.forEach(item => {
      totalUnread += item.unread;
      if (item.type === 'group') {
        groupUnread += item.unread;
      } else {
        personalUnread += item.unread;
      }
    });
    
    this.setData({
      totalUnread,
      groupUnread,
      personalUnread
    });
  },
  
  // 跳转到聊天页面
  navigateToChat: function(e) {
    // 获取点击的通知项数据
    const type = e.currentTarget.dataset.type;
    const id = e.currentTarget.dataset.id;
    
    let chatParams = {};
    
    if (type === 'personal') {
      const sender = e.currentTarget.dataset.sender;
      console.log('准备跳转到私聊页面，聊天对象:', sender);
      
      // 从消息页面获取头像
      const avatar = e.currentTarget.dataset.avatar || "https://objectstorageapi.bja.sealos.run/a0qepsyj-001/text/Default%20avatar/d907281-0.png";
      
      chatParams = {
        id: id,
        name: sender,
        avatar: avatar,
        type: 'personal'
      };
    } else if (type === 'group') {
      const name = e.currentTarget.dataset.name;
      const avatar = e.currentTarget.dataset.avatar;
      console.log('准备跳转到群聊页面，群组:', name);
      
      chatParams = {
        id: id,
        name: name,
        avatar: avatar,
        type: 'group'
      };
    }
    
    // 标记为已读
    this.markChatAsRead(type, id);
    
    try {
      // 跳转到聊天页面，并传递参数
      wx.navigateTo({
        url: `/pages/chat/chat?id=${chatParams.id}&name=${encodeURIComponent(chatParams.name)}&avatar=${encodeURIComponent(chatParams.avatar)}&type=${chatParams.type}`,
        success: function() {
          console.log('跳转成功');
        },
        fail: function(error) {
          console.error('跳转失败:', error);
        }
      });
    } catch (error) {
      console.error('跳转过程中出错:', error);
    }
  },
  
  // 标记特定聊天为已读
  markChatAsRead: function(type, id) {
    // 减少相应类型的未读消息数
    let { totalUnread, groupUnread, personalUnread } = this.data;
    let unreadToReduce = 0;
    
    // 模拟获取未读消息数
    if (type === 'group') {
      if (id === 1) unreadToReduce = 12;      // JAVA讨论群
      else if (id === 2) unreadToReduce = 5;  // 算法竞赛小组
      else if (id === 3) unreadToReduce = 5;  // 校园开放日筹备组
      else if (id === 4) unreadToReduce = 2;  // 毕业设计交流群
      
      groupUnread -= unreadToReduce;
    } else if (type === 'personal') {
      if (id === 1) unreadToReduce = 1;      // 陈明辉
      else if (id === 2) unreadToReduce = 3; // 余翔宇
      else if (id === 3) unreadToReduce = 2; // 金波
      else if (id === 4) unreadToReduce = 1; // 伍慧嘉
      else if (id === 5) unreadToReduce = 6; // 张三
      else if (id === 6) unreadToReduce = 4; // 徐一
      
      personalUnread -= unreadToReduce;
    }
    
    totalUnread -= unreadToReduce;
    
    if (unreadToReduce > 0) {
      this.setData({
        totalUnread: Math.max(0, totalUnread),
        groupUnread: Math.max(0, groupUnread),
        personalUnread: Math.max(0, personalUnread)
      });
      console.log(`已将${type} ID:${id}标记为已读`);
    }
  },
  
  onShow: function() {
    // 设置当前页面对应的tabBar索引
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 2
      });
    }
    
    // 更新全局变量
    const app = getApp();
    if (app.globalData) {
      app.globalData.tabBarIndex = 2;
    }
  },
  
  // 其他页面方法...
  // Other methods can be added here...

  /**
   * 切换标签页
   */
  switchTab: function(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      activeTab: tab
    });
  },

  /**
   * 搜索消息
   */
  searchMessages: function(e) {
    const keyword = e.detail.value;
    this.setData({
      searchKeyword: keyword
    });
    // 实际应用中可以根据关键词过滤消息列表
  },

  /**
   * 显示长按操作菜单
   */
  showActionMenu: function(e) {
    const type = e.currentTarget.dataset.type;
    const id = e.currentTarget.dataset.id;
    
    // 查找当前操作的聊天对象
    let currentChat = {};
    if (type === 'group') {
      // 查找群聊
      // 实际应该从服务器获取或本地数据中查找
      
      // 模拟数据
      const isPinned = id === 2; // 模拟算法竞赛小组置顶
      const isMuted = id === 1 || id === 3; // 模拟JAVA讨论群和校园开放日筹备组免打扰
      
      currentChat = {
        type: type,
        id: id,
        isPinned: isPinned,
        isMuted: isMuted
      };
    } else {
      // 查找私聊
      currentChat = {
        type: type,
        id: id,
        isPinned: false,
        isMuted: false
      };
    }
    
    this.setData({
      showMenu: true,
      currentChat: currentChat,
      isPinned: currentChat.isPinned,
      isMuted: currentChat.isMuted
    });
  },

  /**
   * 隐藏长按操作菜单
   */
  hideActionMenu: function() {
    this.setData({
      showMenu: false
    });
  },

  /**
   * 置顶/取消置顶聊天
   */
  togglePinChat: function() {
    const currentChat = this.data.currentChat;
    const isPinned = !this.data.isPinned;
    
    // 实际应用中应该更新到服务器
    
    this.setData({
      isPinned: isPinned
    });
    
    wx.showToast({
      title: isPinned ? '已置顶' : '已取消置顶',
      icon: 'success'
    });
    
    // 关闭菜单
    this.hideActionMenu();
  },

  /**
   * 设置/取消消息免打扰
   */
  toggleMuteChat: function() {
    const currentChat = this.data.currentChat;
    const isMuted = !this.data.isMuted;
    
    // 实际应用中应该更新到服务器
    
    this.setData({
      isMuted: isMuted
    });
    
    wx.showToast({
      title: isMuted ? '已设置消息免打扰' : '已取消消息免打扰',
      icon: 'success'
    });
    
    // 关闭菜单
    this.hideActionMenu();
  },

  /**
   * 标记为已读
   */
  markAsRead: function() {
    const chat = this.data.currentChat;
    console.log('标记为已读:', chat);
    
    // 使用通用方法标记为已读
    this.markChatAsRead(chat.type, chat.id);
    
    this.setData({
      showMenu: false
    });
    
    wx.showToast({
      title: '已标为已读',
      icon: 'success',
      duration: 1500
    });
    
    // 关闭菜单
    this.hideActionMenu();
  },

  /**
   * 删除聊天
   */
  deleteChat: function() {
    const currentChat = this.data.currentChat;
    
    // 实际应用中应该更新到服务器
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除此聊天吗？',
      success: (res) => {
        if (res.confirm) {
          wx.showToast({
            title: '已删除',
            icon: 'success'
          });
        }
        // 关闭菜单
        this.hideActionMenu();
      }
    });
  }
});